package com.ruoyi.system.xcenter.backup;

import com.ruoyi.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@EnableScheduling
public class DBBackup {

    /**
     * 临时表
     */
    private static final String TMP_TABLE_NAME = "datax_tmp";
    /**
     * 数据交换日志表
     */
    private static final String DATAX_CHANGE_LOG_TABLE_NAME = "datax_xchange_log";

    @Autowired
    private DBUtils dbUtils;

    /**
     * 每周2一点执行
     */
    @Scheduled(cron = "0 0 17 ? * 1")
    public void backDataxChangeLog(){
        tableBackJob(DATAX_CHANGE_LOG_TABLE_NAME);
    }

    /**
     *
     * @param tableName
     */
    private void tableBackJob(String tableName){
        String date = DateUtils.dateTime();
        String tmpSql = "CREATE TABLE "+TMP_TABLE_NAME+" LIKE "+tableName;
        String renameSql = "ALTER TABLE "+tableName+" RENAME TO "+tableName+date;
        String recoverSql = "ALTER TABLE "+TMP_TABLE_NAME+" RENAME TO "+tableName;

        dbUtils.excuteQuerySql(tmpSql);
        dbUtils.excuteQuerySql(renameSql);
        dbUtils.excuteQuerySql(recoverSql);

        log.info("{}备份完成{}",tableName,date);
    }
}
